<template>
  <div class="mock-list-container">
    <div class="page-header">
      <h2>Mock API管理</h2>
      <el-button type="primary" @click="createMockAPI">创建Mock API</el-button>
    </div>

    <el-card class="mock-list-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="mockAPIs"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="API名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="path" label="请求路径" min-width="200" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getMethodTagType(row.method)"
              size="small"
            >
              {{ row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click.stop="editMockAPI(row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click.stop="deleteMockAPI(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="mockAPIs.length > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>

      <el-empty v-if="mockAPIs.length === 0 && !loading" description="暂无Mock API" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const mockAPIs = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 获取Mock API列表
const fetchMockAPIs = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/mock')
    mockAPIs.value = response.data
    total.value = response.data.length
    loading.value = false
  } catch (error) {
    console.error('获取Mock API列表失败:', error)
    ElMessage.error('获取Mock API列表失败')
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 根据请求方法获取标签类型
const getMethodTagType = (method) => {
  const methodMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return methodMap[method] || ''
}

// 创建Mock API
const createMockAPI = () => {
  router.push('/mock/create')
}

// 编辑Mock API
const editMockAPI = (id) => {
  router.push(`/mock/edit/${id}`)
}

// 删除Mock API
const deleteMockAPI = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个Mock API吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await axios.delete(`http://localhost:8080/api/mock/${id}`)
    ElMessage.success('删除成功')
    fetchMockAPIs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除Mock API失败:', error)
      ElMessage.error('删除Mock API失败')
    }
  }
}

// 处理分页
const handlePageChange = (page) => {
  currentPage.value = page
  // 实际项目中可能需要调用API进行分页查询
  // 这里简单模拟
}

onMounted(() => {
  fetchMockAPIs()
})
</script>

<style scoped>
.mock-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.mock-list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>